import React, { useEffect, useRef, useState } from 'react';
import './index.less';
import { ProFormText } from '@ant-design/pro-components';
import Iconfont from '@/components/Iconfont';
import { Modal, Select } from 'antd';
import _ from 'lodash';
import type { LocationType, PropsType } from './index.d';
import mockData from './mock';
import { useUnmount } from 'ahooks';
import { getCenter, initLocation, strTolatLng } from './lib';

const QQMapLocationSelect: React.FC<PropsType> = (props) => {
  const { callback, qqMapKey, formRef, name } = props;
  const map = useRef<any>(null);
  const marker = useRef<any>(null);
  const [keyword, setKeyword] = useState<string | undefined>('');
  const [isModalOpen, setIsModalOpen] = useState<boolean>(false);
  const [loading, setLoading] = useState<boolean>(false);
  const [locationList, setLocationList] = useState<any[]>([]);
  const [location, setLocation] = useState<LocationType>(initLocation);
  // 更新标记位
  const updateMarker = (center: any) => {
    map.current.setCenter(center);
    // 更新标记点的位置
    marker.current.setGeometries([
      {
        position: center,
        id: 'marker',
      },
    ]);
  };
  useEffect(() => {
    if (!isModalOpen) {
      setLocation(initLocation);
      setLocationList([]);
      setKeyword(undefined);
      return;
    }
    let currentLocation = { ...location };
    const value = formRef?.current?.getFieldValue([name]);
    if (value) {
      currentLocation = strTolatLng(value);
      setLocation(getCenter(currentLocation.lat, currentLocation.lng));
    }
    const center = getCenter(currentLocation.lat, currentLocation.lng);
    //初始化地图
    map.current = new TMap.Map('qqMap', {
      rotation: 30, //设置地图旋转角度
      pitch: 30, //设置俯仰角度（0~45）
      zoom: 18, //设置地图缩放级别
      center, //设置地图中心点坐标
      minZoom: 12, //此处设置地图的缩放级别  最小值是6
      maxZoom: 22, //此处设置地图的缩放级别  最大值是7
    });
    marker.current = new TMap.MultiMarker({
      map: map.current,
      styles: {
        // 点标记样式
        marker: new TMap.MarkerStyle({
          width: 20, // 样式宽
          height: 30, // 样式高
          anchor: { x: 10, y: 30 }, // 描点位置
        }),
      },
      geometries: [
        {
          position: center,
          id: 'marker',
        },
      ],
    });
  }, [isModalOpen]);
  useEffect(() => {
    return () => {
      map?.current?.destroy();
      if (map) {
        map.current = null;
      }
    };
  }, []);
  useUnmount(() => {
    map?.current?.destroy();
    if (map) {
      map.current = null;
    }
    console.log('执行销毁');
  });
  const search = async (keyword: string) => {
    try {
      setLoading(true);
      // const suggest = new TMap.service.Suggestion({
      //   pageSize: 10, // 返回结果每页条目数
      //   regionFix: false, // 搜索无结果时是否固定在当前城市
      //   servicesk: qqMapKey, // key
      // });
      // const { data, status } = await suggest.getSuggestions({
      //   keyword,
      // });
      const { data, status } = mockData;
      if (status === 0) {
        setLocationList(data ?? []);
      }
    } catch (error: any) {
      console.log('error', error);
    } finally {
      setLoading(false);
    }
  };
  const handleSearch = _.debounce((newValue: string) => search(newValue), 500);
  const handleChange = (newValue: string) => {
    setKeyword(newValue);
    if (!newValue) {
      setLocationList([]);
      return;
    }
    const {
      location: { lat, lng },
    } = locationList.find(({ id }) => id === newValue);
    updateMarker(getCenter(lat, lng));
    setLocation({ lat, lng });
  };
  return (
    <>
      <ProFormText
        placeholder="请选择导航地址"
        required
        disabled
        fieldProps={{
          addonAfter: (
            <>
              <div onClick={() => setIsModalOpen(true)}>
                <Iconfont
                  type="icon-weizhi"
                  style={{ fontSize: 22, color: 'red', cursor: 'pointer' }}
                />
              </div>
              <Modal
                title="位置选择"
                open={isModalOpen}
                maskClosable={false}
                width="65vw"
                onOk={() => {
                  const { lng, lat } = location;
                  formRef?.current?.setFieldsValue({
                    [name]: `${lng},${lat}`,
                  });
                  callback?.(lat, lng);
                  setIsModalOpen(false);
                }}
                onCancel={() => setIsModalOpen(false)}
              >
                <Select
                  value={keyword}
                  showSearch
                  style={{ width: '100%', marginBottom: 20 }}
                  placeholder="请输入关键字"
                  defaultActiveFirstOption={false}
                  suffixIcon={null}
                  filterOption={false}
                  onSearch={handleSearch}
                  onChange={handleChange}
                  loading={loading}
                  notFoundContent={null}
                  options={locationList.map((d) => ({
                    value: d.id,
                    label: d.title,
                  }))}
                />
                <div id="qqMap"></div>
              </Modal>
            </>
          ),
        }}
        {...props}
      />
    </>
  );
};
export default QQMapLocationSelect;
